package com.example.video.util.download;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.video.Enum.Language;
import com.example.video.Enum.videoStatus;
import com.example.video.entity.Account;
import com.example.video.entity.ResponseData;
import com.example.video.entity.Video;
import com.example.video.mapper.VideoMapper;
import com.example.video.util.MD5Utils;
import com.example.video.util.SuffixUtil;
import com.example.video.util.http.HttpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class DownTask {

    @Value("${downLoadPath}")
    private String downloadPath;

    @Value("${ServerUrl}")
    private String serverUrl;

    @Resource
    private VideoMapper videoMapper;

    @Resource
    private HttpUtil httpUtil;




    /**
     * 添加下载任务,异步执行添加任务
     * @param post 带下载的视频信息
     * @param account 视频所属账户id
     */
    public void addTask(ResponseData.Post post, Account account, String now_cursor) {

        // 获取当前时间
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 对象，指定日 期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化当前时间为年月日时间
        String formattedDate = dateFormat.format(currentDate);

//            获取id
        String resourceId = post.getId();

//            创建video对象，用来插入video表
        Video video = new Video();

        List<ResponseData.Media> mediaList = post.getMedias();

        // 遍历medias，并保存medias资源，修改medias的url并保存到video表的medias中
        for(int i=0; i<mediaList.size(); i++) {
//                ResponseData.Media media = mediaList.get(i);

            String resourceUrl = mediaList.get(i).getResource_url();
            String previewUrl = mediaList.get(i).getPreview_url();
            String previewProxyUrl = mediaList.get(i).getPreview_proxy_url();

            if(account.getName() == null || "".equals(account.getName())){
                account.setName( MD5Utils.encryptMD5(account.getUrl()) );
            }

            String savePath =  account.getName() +"/" +formattedDate + "/" + resourceId + "-" + i;
            String ResourceSuffix = SuffixUtil.getSuffix(resourceUrl);


            if (ResourceSuffix == null){
                ResourceSuffix = ".mp4";
            }
            String PreSuffix = ".webp";


            try {
                File directory = new File(downloadPath + account.getName() +"/"+ formattedDate);
                if( !directory.exists() ){
                    directory.mkdirs();
                }
                File pre_directory = new File(downloadPath + account.getName());
                if( !pre_directory.exists() ){
                    pre_directory.mkdirs();
                }

                // 创建 URL 对象
                URL url = new URL(resourceUrl);
                // 打开连接
                URLConnection connection = url.openConnection();

                // 获取输入流
                InputStream inputStream = connection.getInputStream();
                // 创建输出流

                FileOutputStream outputStream = new FileOutputStream( downloadPath+ savePath + ResourceSuffix);
                mediaList.get(i).setResource_url(serverUrl + savePath + ResourceSuffix);

                // 读取数据并写入文件
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                // 关闭流
                outputStream.close();
                inputStream.close();
//                    log.info("下载完成："+savePath);
                if( previewUrl != null && !("").equals(previewUrl)){
                    if(FileUtil.downloadImage(previewUrl,downloadPath + savePath+"_pre-" + i + PreSuffix)){
                        mediaList.get(i).setPreview_url(serverUrl + savePath+"_pre-"+ i +PreSuffix);
                    }
                }else if(previewProxyUrl != null && !("").equals(previewProxyUrl)){
                    if(FileUtil.downloadImage(previewProxyUrl,downloadPath + savePath+"_pre-"+ i +PreSuffix)){
                        mediaList.get(i).setPreview_url(serverUrl + savePath+"_pre-"+ i +PreSuffix);
                    }
                }

                // 下载完成
                video.setCreateTime(currentDate);
                video.setStatus(videoStatus.DOWNLOADING.getStatus());
                video.setErrMsg("");

                // TODO:向视频处理发送信号，可以进行视频处理
                log.info("DownTask -> addTask ->msg:向视频处理发送处理信号 ");
                httpUtil.sendToVideoServer(post.getId(),
                        resourceUrl,
                        Language.getCodeByName(account.getLanguage()),
                        Language.getCodeByName( account.getToLanguage())
                );


            }catch (MalformedURLException urlException){

                log.info(resourceId +"URL 错误："+urlException.getMessage());
                video.setErrCursor(now_cursor);
                video.setErrMsg("URL 错误：" + urlException.getMessage());
                video.setStatus(0);
            } catch (FileNotFoundException e) {
//                    System.err.println("videoDown -> run -> msg : " + e.getClass().getName() + ": " + e.getMessage());
//                    log.info("videoDown -> run -> msg : "+resourceId + "视频下载失败：" + e.getMessage());
//                    log.info("videoDown -> run -> msg : ");
                video.setErrCursor(now_cursor);
                video.setErrMsg("找不到资源：" + e.getMessage());
                video.setStatus(0);
            }catch (ConnectException e) {
                System.err.println("videoDown -> run -> msg : " + e.getClass().getName() + ": " + e.getMessage());
//                    log.info("videoDown -> run -> msg : "+resourceId + "视频下载失败：" + e.getMessage());
//                    log.info("videoDown -> run -> msg : ");
                video.setErrCursor(now_cursor);
                video.setErrMsg("资源无法链接：" +e.getClass().getName() + e.getMessage());
                video.setStatus(0);
            }catch (IOException e) {
                System.err.println("videoDown -> run -> msg : " + e.getClass().getName() + ": " + e.getMessage());
//                    log.info("videoDown -> run -> msg : "+resourceId + "视频下载失败：" + e.getMessage());
//                    log.info("videoDown -> run -> msg : ");
                video.setErrCursor(now_cursor);
                video.setErrMsg("读写错误：" + e.getClass().getName() + ": " + e.getMessage());
                video.setStatus(0);
            }
        }

        video.setAccountId(account.getId());
        video.setResourceId(post.getId());
        // 对文本进行处理
        //移除 [超话]
        String withoutSuperTopic = post.getText().replaceAll("\\[超话\\]", "");
        //格式化 #*# 这种格式的句子为 #*，并将后面的 # 替换为空格
        String formatted = withoutSuperTopic.replaceAll("#([^# ]+)#", "#$1 ");

        video.setTitle(formatted);
        video.setMedias(mediaList.toString());


        Video result_video = videoMapper.selectOne(new QueryWrapper<Video>().eq("resource_id",video.getResourceId()));
//        若该资源id不存在存在
//            log.info("videoDown -> item -> msg：插入："+video.getResourceId()+" \rcursor: "+now_cursor);
        if( result_video == null ){
//                log.info("videoDown -> item -> msg：资源不存在！");
            videoMapper.insert(video) ;
        }else{
//                log.info("videoDown -> item -> msg：资源已存在，进行更新！");
            video.setId(result_video.getId());
            videoMapper.updateById(video);
        }
    }

}
